/**
 * @author yexiebao
 * @date 2025/5/15
 */

public class SwapPairs {
    //迭代
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode virtualHead = new ListNode();
        virtualHead.next = head;
        ListNode curr = virtualHead;
        while(curr.next != null && curr.next.next != null) {
            ListNode first = curr.next;
            ListNode second = curr.next.next;
            first.next = second.next;
            second.next = first;
            curr.next = second;
            curr = first;
        }
        head = virtualHead.next;
        return head;
    }
    //递归
    public ListNode swapPairsUsingRecursion(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        //创建一个新的头节点指向第二个节点
        ListNode newNode = head.next;
        //第一个节点指向newNode.next即第三个节点
        head.next  = swapPairsUsingRecursion(newNode.next);
        //交换
        newNode.next = head;
        return newNode;
    }
}